/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
**/

package edu.cmu.fithub.actions;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.RegisterForm;
import edu.cmu.fithub.formbeans.RegisterOpenIdForm;

public class RegisterOpenIdAction extends Action {

	private FormBeanFactory<RegisterOpenIdForm> formFactory = FormBeanFactory
			.getInstance(RegisterOpenIdForm.class);

	public RegisterOpenIdAction() {
	}

	public String getName() {
		return "registeropenid.do";
	}

	public String perform(HttpServletRequest request) {
		HttpSession session = request.getSession();

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);

		try {

			User user = new User();
			request.setAttribute("user", user);

			RegisterOpenIdForm form = formFactory.create(request);
			request.setAttribute("registerForm", form);

			if (!form.isPresent()) {
				return "welcome.jsp?doreg=1";
			}

			errors.addAll(form.getValidationErrors());
			Session dbSession = DBHelper.getSessionFactory().openSession();
			
			String userName = (String)session.getAttribute("openid");
			if(userName == null) {
				errors.add("Please authenticate with Identity Provider");
			}
			if (errors.size() > 0) {
					session.setAttribute("registerForm", form);
					return "openidreg.jsp";
			}
			user = new User(userName, 
					new SecureRandom().nextLong()+"",
					Integer.parseInt(form.getAge()),
					form.getFirstName(),
					form.getLastName(),
					form.getTimeZone(),
					form.getEmail(),
					Integer.parseInt(form.getWeight()),
					0,
					false);

			dbSession.beginTransaction();
			dbSession.save(user);
			dbSession.getTransaction().commit();

			// Fetch the items again, since we modified the list
			request.setAttribute("user", user);
			session.setAttribute("user", user);
			session.setAttribute("openid", null);
			return "showHome.do";
			
		} catch (FormBeanException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
	}
}
